#include "teachgamescene.h"
#include "toolkit.h"
#include "resources.h"
#include <QGraphicsPixmapItem>
#include <QGraphicsSceneMouseEvent>
#include "item/teachflyitem.h"
#include "man/teachpopuman.h"
#include "item/indicatelineitem.h"
#include "item/teachptitem.h"
#include <QDebug>
#include "man/teacharmsitem.h"
#include <QSettings>
#include "item/bullettrackitem.h"

TeachGameScene::TeachGameScene(QObject *parent) :
    QGraphicsScene(parent),
    m_bpress(false),
    m_catchItem(NULL),
    m_bRun(true),
    m_bCupRun(false),
    m_bItemFade(false)
{
    ToolKit::m_teachGameScene = this;

    setSceneRect(0.0, 0.0, 640.0, 360.0);

    m_bgitem = addPixmap(QPixmap(":/image/gamebg/gamebg0.jpg"));
    m_bgitem->setPos(0,0);
    m_bgitem->setZValue(0.0);

    m_bgitem1 = addPixmap(QPixmap(":/image/gamebg/gamebg10.jpg"));
    m_bgitem1->setPos(0,319);
    m_bgitem1->setZValue(58.0);

    m_bgitem2 = addPixmap(QPixmap(":/image/gamebg/gamebg20.jpg"));
    m_bgitem2->setPos(62,319);
    m_bgitem2->setZValue(56.0);

    m_bgitem3 = addPixmap(QPixmap(":/image/gamebg/gamebg30.jpg"));
    m_bgitem3->setPos(256,319);
    m_bgitem3->setZValue(54.0);

    m_HPStick = addPixmap(QPixmap(":/image/gamebg/HPStick.jpg"));
    m_HPStick->setPos(62,338);
    m_HPStick->setZValue(57.0);

    m_ScoreStick = addPixmap(QPixmap(":/image/gamebg/ScoreStick.jpg"));
    m_ScoreStick->setPos(18,338);
    m_ScoreStick->setZValue(55.0);

    creatFly();
    createMan();

    m_IndicateLineItem = new IndicateLineItem();
    m_IndicateLineItem->setPos(0.0,0.0);
    m_IndicateLineItem->setZValue(2.0);
    addItem(m_IndicateLineItem);

    m_ptitem = new TeachPtItem();
    m_ptitem->setPos(0.0,0.0);
    m_ptitem->setZValue(2.0);
    addItem(m_ptitem);

    m_movetimer.setInterval(100);
    connect(&m_movetimer,SIGNAL(timeout()),this,SLOT(moveMan()));

    m_StartPromptItem = addPixmap(QPixmap());
    m_StartPromptItem->setZValue(100);

    m_startPromptTiemer.setInterval(100);
    connect(&m_startPromptTiemer,SIGNAL(timeout()),this,SLOT(StartAnima()));

    m_OverTimer.setInterval(100);
    connect(&m_OverTimer,SIGNAL(timeout()),this,SLOT(OverGame()));

//    m_btItem = new BulletTrackItem();
//    m_btItem->setZValue(2);
//    addItem(m_btItem);
}

void TeachGameScene::init()
{
    m_IndicateLineItem->m_ptarr.clear();
    m_IndicateLineItem->m_pixmap->fill(0);
    m_IndicateLineItem->m_brun = true;
    m_IndicateLineItem->setVisible(true);

    m_teachMan->setPos(-70,m_teachMan->m_y);
    if(m_teachMan->m_bleft)
    {
        m_teachMan->Turn();
    }
    m_teachMan->m_bCallCup = false;
    m_teachMan->m_linelist.clear();
    m_teachMan->m_PathList.clear();
    m_teachMan->setVisible(true);
    m_teachMan->m_bRun = false;
    m_teachMan->SetAnimaType(GO_TP);
    m_teachMan->m_bCalculation = false;
    m_teachMan->m_lineTp = PT_LTP;

    m_teachCup->setPos(-70,m_teachCup->m_y);
    if(m_teachCup->m_bleft)
    {
        m_teachCup->Turn();
    }
    m_teachCup->m_linelist.clear();
    m_teachCup->m_PathList.clear();
    m_teachCup->setVisible(true);
    m_teachCup->m_bRun = false;
    m_bCupRun = false;
    m_teachCup->SetAnimaType(GO_TP);
    m_teachCup->m_bCalculation = false;
    m_teachCup->m_lineTp = PT_LTP;

    m_flylist[2]->m_bBeginShowIndicate = false;
    foreach(TeachFlyItem* item,m_flylist)
    {
        item->m_bRun = true;
    }

    m_ptitem->m_pixmap->fill(0);

    m_bRun = true;

    m_movetimer.start();

    if(ToolKit::m_bVoice)
    {
        ToolKit::playBg(1);
        ToolKit::m_bgameVoice = true;
    }

    m_bpress = false;

    m_StartPromptItem->setVisible(true);
    m_StartPromptItem->setOpacity(0.0);
    m_StartPromptItem->setPixmap(ToolKit::m_rc->m_PromatReadyImage);
    m_StartPromptItem->setPos(205,149);

    if(ToolKit::m_bVoice)
        ToolKit::playSound(1);

    m_startPromptTiemer.start();
}

void TeachGameScene::GameContinue()
{
    m_IndicateLineItem->m_brun = true;
    if(!m_bpress)
    {
        m_teachMan->m_bRun = true;
        if(m_bCupRun)
            m_teachCup->m_bRun = true;
    }
    foreach(TeachFlyItem* item,m_flylist)
    {
        item->m_bRun = true;
    }

    if(ToolKit::m_bVoice)
    {
        ToolKit::playBg(1);
        ToolKit::m_bgameVoice = true;
    }

    m_bRun = true;
}

void TeachGameScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(QRectF(580.0,320.0,60.0,40.0).contains(event->scenePos()))
    {
        if(ToolKit::m_bVoice)
            ToolKit::playSound(2);

        pause();
    }
    else if(m_bpress)
    {
        QList<QGraphicsItem *> list = items(event->scenePos(),Qt::IntersectsItemShape,Qt::DescendingOrder);
        if(!list.isEmpty() && list.at(0)->zValue() >= 3.0 && list.at(0)->zValue() <= 53)
        {
            m_catchItem = static_cast<ManItem*>(list.at(0));
            if(m_catchItem->ClickRc().contains(event->scenePos()))
            {
                if(ToolKit::m_bVoice)
                    ToolKit::playSound(3);

                m_startPt = m_catchItem->StartPoint();
                m_catchItem->m_linelist.append(m_startPt);
                m_catchItem->m_PathList.append(m_startPt);
                m_catchItem->m_bCalculation = false;

                m_bmoveEnable = true;
            }
        }
        else
        {
            m_catchItem = NULL;
        }
    }
}

void TeachGameScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if(m_catchItem != NULL)
    {
        if(m_bmoveEnable)
        {
            if(IsArrive(event->scenePos()))
            {
                qWarning()<<m_catchItem->m_linelist.count();

                m_catchItem->m_lineTp = Hatch_LTP;
                m_catchItem->m_ihitNum = 0;
                m_catchItem->SetAnimaType(CATCH_TP);
                m_catchItem->SetCoverType(COMMON_CTP);
                m_catchItem->m_Interval = 0.0;

                m_bmoveEnable = false;

                m_catchItem->m_bCalculation = true;
                m_catchItem->m_bRun = true;
                m_IndicateLineItem->setVisible(false);
                m_teachMan->m_bShowIndicate = false;
                m_teachCup->m_bShowIndicate = false;
                m_flylist[2]->m_bBeginShowIndicate = false;

                m_bpress = false;
            }
            else
            {
                if(fillPt(m_startPt,event->scenePos()))
                {
                    m_startPt = m_catchItem->m_linelist.last();
                }
            }
        }
    }
}

void TeachGameScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if(m_catchItem != NULL && m_catchItem->m_mananimatp != CATCH_TP)
    {
        m_catchItem->m_linelist.clear();
        m_catchItem->m_PathList.clear();
    }
}

void TeachGameScene::pause()
{
    m_IndicateLineItem->m_brun = false;
    m_teachMan->m_bRun = false;
    m_teachCup->m_bRun = false;
    foreach(TeachFlyItem* item,m_flylist)
    {
        item->m_bRun = false;
    }

    if(ToolKit::m_bVoice)
    {
        ToolKit::stopBg(1);
        ToolKit::m_bgameVoice = false;
    }

    m_bRun = false;
    emit showPause();
}

void TeachGameScene::creatFly()
{
    for(int i = 0; i < 5; ++i)
    {
        TeachFlyItem* flyitem = new TeachFlyItem();
        flyitem->setPos(i * 130 - 30,FLOAT_RANGE / 2);
        flyitem->setZValue(1.0);
        flyitem->m_iIndex = i;
        if(i == 2)
        {
            flyitem->m_bOpening = true;
        }
        connect(flyitem,SIGNAL(FlyHurt(int)),this,SLOT(FlyHurt(int)));
        addItem(flyitem);
        m_flylist.append(flyitem);
    }
}

void TeachGameScene::FlyHurt(const int &iHurt)
{
}

void TeachGameScene::createMan()
{
    m_teachMan = new TeachPopuMan(BAOZI_MTP);
    qWarning()<<sizeof(QImage);
    connect(m_teachMan,SIGNAL(RunOut(int,ManItem*)),this,SLOT(PopulaceRunOut(int,ManItem*)));
    if(m_teachMan->m_bleft)
    {
        m_teachMan->setX(-70);
        m_teachMan->Turn();
    }
    m_teachMan->SetDetectX();
    m_teachMan->setZValue(3);
    m_teachMan->SetAnimaType(GO_TP);
    connect(m_teachMan,SIGNAL(ShowIndicate()),this,SLOT(ShowIndicate()));
    addItem(m_teachMan);

    m_teachCup = new TeachArmsItem();
    connect(m_teachCup,SIGNAL(ShowIndicate()),this,SLOT(CupShowIndicate()));
    if(m_teachCup->m_bleft)
    {
        m_teachCup->setX(-70);
        m_teachCup->Turn();
    }
    m_teachCup->SetDetectX();
    m_teachCup->setZValue(3);
    m_teachCup->SetAnimaType(GO_TP);
    m_teachCup->m_bRun = false;
    addItem(m_teachCup);
}

void TeachGameScene::ShowIndicate()
{
    m_teachMan->m_bRun = false;
    QPointF startPt(m_teachMan->StartPoint());
    QPointF endPt(m_flylist[2]->DoorPoint());
    qreal length = QLineF(startPt,endPt).length();
    if(length > POINT_INTERVAL)
    {
        int icount = static_cast<int>(length / POINT_INTERVAL) + 1;
        QPointF pt = endPt - startPt;
        for(int i = 1 ; i < icount;++i)
        {
            m_IndicateLineItem->m_ptarr.append(startPt + pt * static_cast<qreal>(i) / icount);
        }
    }
    m_IndicateLineItem->m_timer.start();
    m_flylist[2]->m_bBeginShowIndicate = true;

    m_teachMan->m_bShowIndicate = true;

    m_bpress = true;
}


bool TeachGameScene::IsArrive(const QPointF& pt)
{
    bool bArrive = false;
    foreach(TeachFlyItem* item ,m_flylist)
    {
        if(item->m_bOpen && item->DecisionRc().containsPoint(pt,Qt::OddEvenFill))
        {
            bArrive = true;

            item->m_manItem = m_catchItem;
            m_catchItem->m_flyItem = item;

            if(!m_catchItem->m_linelist.isEmpty())
            {
                QPointF lastPt = m_catchItem->m_linelist.last();
                QPointF doorPt = item->DoorPoint();

                fillPt(lastPt,doorPt);

                m_catchItem->m_linelist.append(doorPt);
                m_catchItem->m_PathList.append(doorPt);
            }
            break;
        }
    }

    return bArrive;
}

bool TeachGameScene::fillPt(const QPointF &startPt, const QPointF &endPt)
{
    qreal length = QLineF(startPt,endPt).length();
    bool result = false;
    if(length > POINT_INTERVAL)
    {
        int icount = static_cast<int>(length / POINT_INTERVAL) + 1;
        QPointF pt = endPt - startPt;
        for(int i = 1 ; i < icount;++i)
        {
            m_catchItem->m_linelist.append(startPt + pt * static_cast<qreal>(i) / icount);
            m_catchItem->m_PathList.append(startPt + pt * static_cast<qreal>(i) / icount);
        }
        result = true;
    }
    return result;
}

void TeachGameScene::moveMan()
{
    if(m_bRun)
    {
        if(m_catchItem != NULL &&  m_catchItem->isVisible())
        {
            if(!m_catchItem->m_linelist.isEmpty() && m_catchItem->m_mananimatp == CATCH_TP)
            {
                m_catchItem->setPos(m_catchItem->pos() + m_catchItem->m_linelist.first()
                                    - m_catchItem->StartPoint());
            }

            m_ptitem->render();
            m_ptitem->update();

            m_catchItem->Calculation();
        }
    }
}

void TeachGameScene::CupTeach()
{
    m_IndicateLineItem->m_ptarr.clear();

    m_teachMan->setPos(-30,m_teachMan->m_y);
    m_teachMan->SetDetectX();
    m_teachMan->SetAnimaType(GO_TP);
    m_teachMan->m_bCallCup = true;
    m_teachMan->setVisible(true);
    m_teachMan->m_bRun = true;
}

void TeachGameScene::PopulaceRunOut(const int& PopType, ManItem* item)
{
    m_teachCup->m_bRun = true;
    m_bCupRun = true;
}

void TeachGameScene::CupShowIndicate()
{
    m_teachCup->m_bRun = false;
    QPointF startPt(m_teachCup->StartPoint());
    QPointF endPt(m_flylist[2]->DoorPoint());
    qreal length = QLineF(startPt,endPt).length();
    if(length > POINT_INTERVAL)
    {
        int icount = static_cast<int>(length / POINT_INTERVAL) + 1;
        QPointF pt = endPt - startPt;
        for(int i = 1 ; i < icount;++i)
        {
            m_IndicateLineItem->m_ptarr.append(startPt + pt * static_cast<qreal>(i) / icount);
        }
    }
    m_IndicateLineItem->m_timer.start();
    m_IndicateLineItem->setVisible(true);
    m_flylist[2]->m_bBeginShowIndicate = true;

    m_teachCup->m_bShowIndicate = true;

    m_bpress = true;
}

void TeachGameScene::CupIn()
{
    m_bRun = false;

    if(ToolKit::m_level == ToolKit::m_curlevel && ToolKit::m_level < 19)
    {
        ToolKit::m_level += 1;
        QSettings settings("MySoft", "level");
        settings.setValue("Main/level",ToolKit::m_level);
    }

    m_StartPromptItem->setPixmap(ToolKit::m_rc->m_PromatClearImage);
    m_StartPromptItem->setPos(202,149);
    m_StartPromptItem->setVisible(true);

    if(ToolKit::m_bVoice)
        ToolKit::playSound(30);
    m_OverTimer.start();
}

void TeachGameScene::StartAnima()
{
    if(!m_bItemFade)
    {
        m_StartPromptItem->setOpacity(m_StartPromptItem->opacity() + 0.1);
        if(m_StartPromptItem->opacity() >= 1.0)
        {
            if(ToolKit::m_bVoice)
                ToolKit::playSound(0);

           m_bItemFade = true;
           m_StartPromptItem->setPixmap(ToolKit::m_rc->m_PromatGoImage);
           m_StartPromptItem->setPos(263,149);
        }
    }
    else if(m_bItemFade)
    {
       m_StartPromptItem->setOpacity(m_StartPromptItem->opacity() - 0.1);
       if(m_StartPromptItem->opacity() <= 0.0)
       {
          m_bItemFade = false;
          m_startPromptTiemer.stop();
          m_StartPromptItem->hide();

          m_teachMan->m_bRun = true;
       }
    }
}

void TeachGameScene::OverGame()
{
    if(!m_bItemFade)
    {
        m_StartPromptItem->setOpacity(m_StartPromptItem->opacity() + 0.1);
        if(m_StartPromptItem->opacity() >= 1.0)
        {
           m_bItemFade = true;
        }
    }
    else if(m_bItemFade)
    {
       m_StartPromptItem->setOpacity(m_StartPromptItem->opacity() - 0.1);
       if(m_StartPromptItem->opacity() <= 0.0)
       {
          m_bItemFade = false;
          m_OverTimer.stop();
          m_StartPromptItem->hide();

          emit GameOver(false);
       }
    }
}
